<template>
  <div>
    <div class="no-up-box">
      <div v-if="!src">
        <i class="el-icon-upload"></i>
        <span>点击上传图片</span>
      </div>
      <el-image class="up-box-src" :src="$oss_url + src +  '?x-oss-process=image/resize,h_300'" fit="cover" v-if="src"></el-image>
      <input type="file" class="up-box-file" @change="upFiles($event)" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      src: ""
    };
  },
  methods: {
    upFiles(e) {
      var file = e.currentTarget.files;
      this.fileUpload(file[0]);
    },
    fileUpload(img) {
      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      var img_type = arr[1];
      let OSS = require("ali-oss");
      let client = new OSS({
        region: "oss-cn-hangzhou",
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
        accessKeyId: "LTAIWdxCuPiIzLfm",
        accessKeySecret: "z1zLih5CgWNkWfuzHj7SbpJKVdME2a",
        bucket: "ykp-new"
      });
      // client.options.endpoint.protocol = "https:";
      //获取当前时间
      var date = new Date();
      var file_name =
        date.getFullYear() +
        "/" +
        (date.getMonth() + 1) +
        "/" +
        date.getDate() +
        "/" +
        date.getHours() +
        "_" +
        date.getMinutes() +
        "_" +
        date.getSeconds() +
        "_" +
        date.getMilliseconds();
      let filename = "/active/cover/" + file_name + "." + img_type;
      let res_file = img;
      let that = this;
      async function put() {
        try {
          //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          let result = await client
            .multipartUpload(filename, res_file, {
              progress: percentage => {
                //console.log(percentage); // 上传文件进度
              }
            })
            .then(res => {
              that.src = res.name;
              that.$emit('change',res.name);
            })
            .catch(err => {
              return that.toast(0, "上传失败");
            });
        } catch (e) {
          return that.toast(0, "上传失败");
        }
      }
      put();
    }
  }
};
</script>

<style>
.up-box-src {
  width: 300px;
  height: 150px;
}
.no-up-box {
  width: 300px;
  height: 150px;
  border: 1px dashed #c1c1c1;
  border-radius: 5px;
  text-align: center;
  line-height: 150px;
  color: #666;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}
.no-up-box span {
  margin-left: 5px;
}
.up-box-file {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}
</style>